package org.softmed.action.implementation;

import groovy.lang.Script;
import groovy.util.GroovyScriptEngine;

import java.io.File;
import java.io.InputStream;

import org.softmed.action.ActionStep;
import org.softmed.action.builder.ActionStepBuilder;
import org.softmed.action.description.ActionStepDescription;
import org.softmed.action.resolver.ActionStepResolver;

import org.softmed.filehandling.FileUtil;
import org.softmed.groovy.utils.GroovyCache;

import com.google.inject.Inject;

public class DefaultGroovyScriptActionStepResolver implements
		ActionStepResolver {

	@Inject
	GroovyCache groovyCache;

	FileUtil util = new FileUtil();

	@Override
	public ActionStep instantiate(ActionStepDescription description)
			throws Throwable {
		String origin = description.getSource();

		String path = origin.replace('.', '/');
		path += ".groovy";

		// String correctPath = util.getRootPath() + path;
		// correctPath = util.fixPath(correctPath);

		File file = util.getFile(path);

		if (file == null || !file.exists())
			return null;

		// if (!groovyCache.exists(path))
		// return null;

		// Script script = null;
		// try {
		// script = groovyCache.getScript(correctPath);
		// } catch (Throwable t) {
		// // t.printStackTrace();
		// return null;
		// }

		// InputStream stream = this.getClass().getClassLoader()
		// .getResourceAsStream(path);
		//		
		// if (stream != null) {
		return new GroovyScriptActionStep(path, groovyCache);
		// }
		// return null;

	}

	public GroovyCache getGroovyCache() {
		return groovyCache;
	}

	public void setGroovyCache(GroovyCache groovyCache) {
		this.groovyCache = groovyCache;
	}

}
